package org.linlinjava.litemall.admin.task;

import org.linlinjava.litemall.core.task.TaskService;
import org.linlinjava.litemall.db.domain.LitemallActivity;
import org.linlinjava.litemall.db.service.LitemallActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;

@Component
public class ActivityTaskStartupRunner implements ApplicationRunner {

    @Autowired
    private LitemallActivityService activityService;

    @Autowired
    private TaskService taskService;

    @Override
    public void run(ApplicationArguments args) {
        List<LitemallActivity> activityList = activityService.queryByState(Collections.singletonList(LitemallActivity.StateEnum.ISSUING.getCode()));
        for (LitemallActivity activity : activityList) {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime expire = activity.getEndTime();

            if (expire.isBefore(now)) {
                // 已经过期，马上加入队列执行
                taskService.addTask(new ActivityExpiredTask(activity.getId(), 0L));
            } else {
                // 还没过期，设置延迟执行时间 则加入延迟队列
                long delay = ChronoUnit.MILLIS.between(now, expire);
                taskService.addTask(new ActivityExpiredTask(activity.getId(), delay));
            }

            LocalDateTime startTime = activity.getStartTime();
            if (startTime.isBefore(now)) {
                // 已经到开始时间，马上加入队列执行
                taskService.addTask(new ActivityStartTask(activity.getId(), 0L));
            } else {
                // 还没到开始时间，设置延迟执行时间 加入延迟队列
                long delay = ChronoUnit.MILLIS.between(now, startTime);
                taskService.addTask(new ActivityStartTask(activity.getId(), delay));
            }
        }
    }
}
